package com.zzyl.job;

import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceDataMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class MyTask {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AlertRuleService alertRuleService;

    /**
     * 定时删除设备上报的数据
     */
    @Scheduled(cron = "0 0 23 L * ?")
    public void deleteDeviceDataTask() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime time = now.minusDays(30);
        String finalTime = time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        deviceDataMapper.deleteDeviceData(finalTime);
    }

    /**
     * 定时查询设备报警数据
     */
    @Scheduled(cron = "0 * * * * ?")
    public void deviceDataAlertFilter() {
        //1. 查询所有的规则
        List<AlertRuleVo> ruleList = alertRuleMapper.queryAlertRule(null, null, null);

        //2. 判断规则是否为空, 如果为空则return, 不再往下执行
        if (ObjectUtil.isEmpty(ruleList)) {
            return;
        }

        //3. 从redis中获取到设备的最新的数据(获取所有设备的数据)
        List<Object> jsonList = redisTemplate.opsForHash().values(Constants.DEVICE_ALL_DATA);

        //4. 判断redis中获取的数据是否为空, 如果为空则return
        if (ObjectUtil.isEmpty(jsonList)) {
            return;
        }

        //5. 把json格式的数据转换为vo格式的数据
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        jsonList.stream().forEach(jsonStr -> {
            deviceDataVoList.addAll(JSONUtil.toList((String) jsonStr, DeviceDataVo.class));
        });

        //6. 遍历每一个数据, 然后检验是否合法
        deviceDataVoList.stream().forEach(vo -> {
            alertRuleService.alertFilter(vo);
        });
    }

}
